var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var cors = require("cors");
const { v4: uuidv4 } = require("uuid");

const WebSocket = require("ws");

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");

var app = express();
app.use(cors());

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/users", usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

const wss = new WebSocket.Server({ port: 3003 });

// 处理 HTTP 请求
app.get("/", (req, res) => {
  res.send("Hello from Express!");
});

const clients = new Map();
var list = [
  "周三下午的课改到周四下午上",
  "明年1月10日开始放寒假",
  "3月3日开学，请相互转告",
  "下周开始学习微信小程序",
];
var index = 0;

// 处理 WebSocket 连接
wss.on("connection", (ws) => {
  const clientId = uuidv4(); // 生成唯一标识
  clients.set(clientId, ws);

  ws.on("message", (message) => {
    console.log(message + "");
    // ws.send(`You said: ${message}`);
    if (message + "" === "hi") {
      setInterval(() => {
        ws.send(list[index % 3]);
        index++;
      }, 5000);
    }
  });

  ws.on("close", () => {
    clients.delete(clientId);
  });

  // setInterval(() => {
  //   wss.clients.forEach(function each(client) {
  //     if (client.readyState === WebSocket.OPEN) {
  //       client.send(list[index % 3]);
  //       index++;
  //     }
  //   });
  // }, 5000);
});

module.exports = app;
